package com.zhentao.controller;

import com.zhentao.pojo.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class FreemarkerTestController {
    @RequestMapping("/t1")
    public String t1(Model model){
        //传递一个文本
        model.addAttribute("name","张三");

        //对象
        Student student=new Student();
        student.setName("小明");
        student.setAge(11);
        model.addAttribute("student",student);

        Student student2 =new Student();
        student2.setName("小红");
        student2.setAge(12);
        model.addAttribute("student2",student2);

        //list
        List list=new ArrayList();
        list.add(student);
        list.add(student2);
        model.addAttribute("stus",list);

        //map
        Map<String,Object> map=new HashMap<>();
        map.put("stu1",student);
        map.put("stu2",student2);

        model.addAttribute("stuMap",map);

        return "01-text";
    }

    @Autowired
    private Configuration configuration;

    @ResponseBody
    @RequestMapping("/createHtml")
    public String createHtml() throws IOException, TemplateException {
        Template template = configuration.getTemplate("02.ftl");
        //对象
        Student student=new Student();
        student.setName("小明");
        student.setAge(11);

        Student student2 =new Student();
        student2.setName("小红");
        student2.setAge(12);
        //list
        List list=new ArrayList();
        list.add(student);
        list.add(student2);

        Map<String,Object> map = new HashMap<>();
        map.put("stus", list);
        map.put("stu1", student);
//        template.process(map, new FileWriter("D://03.html"));
//        template.process(map, new FileWriter("C:\\Users\\86132\\Desktop\\03.html"));
        template.process(map, new FileWriter("C://Users//86132//Desktop//03.html"));

        return "success";
    }

}
